package com.example.project.controller;


import com.example.project.model.PageInfo;
import com.example.project.model.PageInfo.Page;
import com.example.project.model.Result;
import com.example.project.model.Student;
import com.example.project.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;


/**
 * @author top
 */
@RestController
@RequestMapping(value = "/api/student")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @GetMapping(value = "/list/{pageNum}/{pageSize}")
    public Result<PageInfo<Student>> list(@PathVariable Integer pageNum, @PathVariable Integer pageSize) {
        long total = studentService.count();
        Page page = Page.page(pageNum, pageSize, total);
        List<Student> students = studentService.selectAllByPage(page.getOffset(), page.getPageSize());
        PageInfo<Student> pageInfo = new PageInfo<>(students, page.getPageNum(), page.getPageSize(), total);
        return Result.ok(2000, "success", pageInfo);
    }

    @GetMapping(value = "/search/{name}")
    public Result<List<Student>> search(@PathVariable String name) {
        List<Student> students = studentService.selectByName(name);
        return Result.ok(2000, "success", students);
    }

    @GetMapping(value = "/number/{number}")
    public Result<Student> search(@PathVariable Long number) {
        Student student = studentService.selectByNumber(number);
        return Result.ok(2000, "success", student);
    }

    @GetMapping(value = "/detail/{studentId}")
    public Result<Student> detail(@PathVariable Long studentId) {
        Student student = studentService.selectOne(studentId);
        return Result.ok(2000, "success", student);
    }

    @DeleteMapping(value = "/delete/{studentId}")
    public Result<Integer> students(@PathVariable Long studentId) {
        int i = studentService.delete(studentId);
        return Result.ok(2000, "success", i);
    }

    @PostMapping(value = "/save")
    public Result<Integer> save(@RequestBody @Valid Student student) {
        int i = studentService.saveOrUpdate(student);
        return Result.ok(2000, "success", i);
    }

}
